package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.vo.IotMsgNotifyData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备数据Service业务层处理
 *
 * @author alexis
 * @date 2025-03-08
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceDataPageReqDto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto deviceDataPageReqDto) {
        // 创建分页对象
        Page<DeviceData> page = new Page<>(deviceDataPageReqDto.getPageNum(), deviceDataPageReqDto.getPageSize());
        // 创建查询条件对象
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotNull(deviceDataPageReqDto.getDeviceName()), DeviceData::getDeviceName, deviceDataPageReqDto.getDeviceName())
                .eq(ObjectUtil.isNotNull(deviceDataPageReqDto.getFunctionId()), DeviceData::getFunctionId, deviceDataPageReqDto.getFunctionId())
                .between(ObjectUtil.isNotNull(deviceDataPageReqDto.getStartTime()) && ObjectUtil.isNotNull(deviceDataPageReqDto.getEndTime()), DeviceData::getAlarmTime, deviceDataPageReqDto.getStartTime(), deviceDataPageReqDto.getEndTime());
        // 执行查询
        page = deviceDataMapper.selectPage(page, queryWrapper);
        TableDataInfo<DeviceData> table = new TableDataInfo<>(page.getRecords(), (int) page.getTotal());
        table.setCode(200);
        return table;
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        // 获取设备iotId
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        // 根据设备iotId查询设备信息
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(device)) {
            throw new RuntimeException("设备不存在");
        }
        // 创建集合存取数据
        List<DeviceData> deviceDataList = new ArrayList<>();
        // 获取上报数据
        iotMsgNotifyData.getBody().getServices().forEach(item -> {
            Map<String, Object> properties = item.getProperties();
            if (ObjectUtil.isEmpty(properties)) {
                return;
            }
            // 处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(item.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            // 日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            properties.forEach((k, v) -> {
                DeviceData deviceData = DeviceData.builder()
                        .iotId(iotId)
                        .deviceName(device.getDeviceName())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(k)
                        .accessLocation(device.getRemark())
                        .deviceDescription(device.getDeviceDescription())
                        .dataValue(v + "")
                        .locationType(device.getLocationType())
                        .alarmTime(alarmTime)
                        .physicalLocationType(device.getPhysicalLocationType())
                        .build();
                deviceDataList.add(deviceData);
            });
        });
        // 批量插入数据
        if (!saveBatch(deviceDataList)) {
            throw new RuntimeException("批量插入数据失败");
        }
        // 批量插入redis
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA , device.getIotId(), deviceDataList);

    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }
}
